package top.jle.spring.basic.fis.generators;

import cn.hutool.core.util.IdUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CodeGenerator {

    private static final String CODE_SEED = "0123456789abcdefghijklmnopqrstuvwxyz";

    private static final Map<Integer,Integer> LENMAP = Map.of(10,34,12,20,14,13);

    /**
     * 雪花算法生成10位不重复的Code
     * @author jim.lee
     * @date 2022/7/25 16:45
     */
    public static String generate(){

        return generate(10);
    }

    public static String generate12(){

        return generate(12);
    }

    public static String generate14(){

        return generate(14);
    }

    private static String generate(int len){
        long n = IdUtil.getSnowflakeNextId();
        n = Long.parseLong(Long.toString(n).substring(3));
        BigDecimal divide = new BigDecimal(LENMAP.get(len));
        BigDecimal decimal = new BigDecimal(n);
        StringBuilder res = new StringBuilder();
        while (BigDecimal.ZERO.compareTo(decimal) != 0){
            BigDecimal[] divRes = decimal.divideAndRemainder(divide);
            decimal = divRes[0];
            res.insert(0, CODE_SEED.charAt(divRes[1].intValue()));
        }
        return res.toString();
    }


}
